package cn.cool.config;

import cn.cool.types.annotation.DCCValue;
import cn.cool.types.common.Constants;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
@Slf4j
@RequiredArgsConstructor
public class DCCValueBeanFactory implements BeanPostProcessor {
    private static final String BASE_CONFIG_PATH = "group_buy_market_dcc_";

    private final RedissonClient redissonClient;

    private final Map<String, Object> dccObject = new ConcurrentHashMap<>();

    @Bean
    public RTopic dccRedisTopicListener(RedissonClient redissonClient) {
        RTopic topic = redissonClient.getTopic("group_buy_market_dcc");
        topic.addListener(String.class, new MessageListener<String>() {
            @Override
            public void onMessage(CharSequence charSequence, String s) {
                String[] split = s.split(Constants.SPLIT);

                String attribute = split[0];
                String key = BASE_CONFIG_PATH + split[0];
                String value = split[1];

                RBucket<String> bucket = redissonClient.getBucket(key);
                boolean exists = bucket.isExists();
                if (!exists) return;
                bucket.set(value);

                Object objBean = dccObject.get(key);
                if (objBean == null) return;

                Class<?> objBeanClass = objBean.getClass();
                if (AopUtils.isAopProxy(objBeanClass)) {
                    objBeanClass = AopUtils.getTargetClass(objBean);
                }

                try {
                    Field field = objBeanClass.getDeclaredField(attribute);
                    field.setAccessible(true);
                    field.set(objBean, value);
                    field.setAccessible(false);
                } catch (Exception e) {
                    throw new RuntimeException("设置属性发生错误");
                }
            }
        });
        return topic;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 为了避免是代理类
        if ("dccService".equals(beanName)) {
            System.out.println();
        }
        Class<?> targetBeanClass = bean.getClass();
        Object targetBeanObject = bean;

        if (AopUtils.isAopProxy(bean)) {
            targetBeanClass = AopUtils.getTargetClass(bean);
            targetBeanObject = AopProxyUtils.getSingletonTarget(bean);
        }

        Field[] fields = targetBeanClass.getDeclaredFields();
        for (Field field : fields) {
            if (!field.isAnnotationPresent(DCCValue.class)) {
                continue;
            }
            DCCValue dccValue = field.getAnnotation(DCCValue.class);
            String value = dccValue.value();
            if (StrUtil.isBlank(value)) {
                throw new RuntimeException("DCCValue annotation value can not be null");
            }

            String[] split = value.split(Constants.COLON);
            String key = BASE_CONFIG_PATH + split[0];
            String defaultValue = split.length == 2 ? split[1] : null;

            String setValue = defaultValue;
            try {
                if (StrUtil.isBlank(defaultValue)) {
                    throw new RuntimeException("DCCValue annotation default value can not be null");
                }

                RBucket<String> bucket = redissonClient.getBucket(key);
                boolean exists = bucket.isExists();
                if (!exists) {
                    bucket.set(defaultValue);
                } else {
                    setValue = bucket.get();
                }

                field.setAccessible(true);
                field.set(targetBeanObject, setValue);
                field.setAccessible(false);
            } catch (Exception e) {
                throw new RuntimeException("设置属性发生错误");
            }
            // 存储起来
            dccObject.put(key, targetBeanObject);
        }
        return bean;
    }
}
